package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.CookieHandler;
import utils.HTMLInputFilter;
import utils.Pair;
import utils.Utils;
import entities.controllers.Cats;
import entities.controllers.Requests;
import entities.controllers.Skills;
import entities.controllers.Users;
import entities.kinds.Skill;

@SuppressWarnings("serial")
public class Handler extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String action = req.getParameter("action");
		if (null != action && !"".equals(action)) {
			if (action.equals("register")) {
				String login = req.getParameter("login");
				String pass = req.getParameter("password");
				String skills = req.getParameter("skills");

				String cleanLogin = new HTMLInputFilter().filter(login);
				String cleanPassword = new HTMLInputFilter().filter(pass);
				String cleanSkills = new HTMLInputFilter().filter(skills);

				if (login.equals(cleanLogin) && pass.equals(cleanPassword)
						&& skills.equals(cleanSkills)) {
					String[] skills_ = skills.split(",");

					if (Users.loginAvailable(login)) {
						String loginEnc = Users.register(login, pass);
						for (String s : skills_) {
							Skills.add(s, login);
							Cats.add(s);
						}

						resp.addHeader("Set-Cookie", "ule=" + loginEnc
								+ "; expires=Fri, 31-Dec-2020 23:59:59 GMT; path=/; HttpOnly");
						resp.setContentType("application/json");
						resp.getWriter().print("{\"success\":true}");
					} else {
						resp.setContentType("application/json");
						resp.getWriter().print(
								"{\"success\":false,\"err\":\"Login is unavialable\"}");
					}
				} else {
					resp.setContentType("application/json");
					resp.getWriter().print(
							"{\"success\":false,\"err\":\"Love hacking? Then eat your shit!\"}");
				}
			} else if (action.equals("login")) {
				String login = req.getParameter("login");
				String password = req.getParameter("password");
				resp.setContentType("application/json");

				if (null != login && null != password) {
					if (Users.loginSuccessful(login, password)) {
						resp.addHeader("Set-Cookie", "ule=" + Utils.SHA256(Utils.MD5(login))
								+ "; expires=Fri, 31-Dec-2020 23:59:59 GMT; path=/; HttpOnly");

						resp.setContentType("application/json");
						resp.getWriter().print("{\"success\":true}");
					} else {
						resp.setContentType("application/json");
						resp.getWriter()
								.print("{\"success\":false,\"err\":\"Check login and password and try again\"}");
					}
				} else {
					resp.setContentType("application/json");
					resp.getWriter()
							.print("{\"success\":false,\"err\":\"Check login and password and try again\"}");
				}

			} else if (action.equals("auth")) {
				Cookie[] cookies = req.getCookies();
				if (null != cookies) {
					String login = CookieHandler.getCookieValue(cookies, "ule");
					ArrayList<Pair<String, String>> messages = Requests.getByReceiver(login);
					if (!login.equals(null)) {
						if (Users.cookieLoginSuccessful(login)) {
							if (messages.size() != 0) {
								resp.setContentType("application/json");
								resp.getWriter().print(
										"{\"success\":true,\"inbox\":{\"msg\":"
												+ Utils.toJSON(messages) + ",\"length\":"
												+ messages.size() + "}}");
							} else {
								resp.setContentType("application/json");
								resp.getWriter().print("{\"success\":true}");
							}
						}
					} else {
						resp.setContentType("application/json");
						resp.getWriter().print("{\"success\":false}");
					}
				} else {
					resp.setContentType("application/json");
					resp.getWriter().print("{\"success\":false}");
				}

			} else if (action.equals("load_content")) {
				String query = req.getParameter("q");
				String cat = req.getParameter("cat");

				if (null != query && !"".equals(query) && null == cat) {
					if ("get_cat".equals(query)) {
						String cats = Cats.getCategories();
						String response = "{\"cats\":[" + cats + "]";

						if (!"".equals(cats)) {
							response += ",\"success\":true";
						} else
							response += ",\"success\":false";
						response += "}";

						resp.setContentType("application/json");
						resp.getWriter().print(response);
					}
				}
				if (null != cat && !"".equals(cat) && !"undefined".equals(cat)
						&& !"null".equals(cat) && null == query) {
					List<Skill> sk = Skills.getByType(cat);
					String response = "{\"users\":{";

					for (Skill s : sk) {
						response += "\"" + s.getUser() + "\":"
								+ Utils.toJSON(Skills.getByUser(s.getUser())) + ",";
					}

					response = response.substring(0, response.length() - 1);
					response += "}}";

					resp.setContentType("application/json");
					resp.getWriter().print(response);
				} else if ("".equals(cat) && null == query) {
					resp.sendRedirect("/#home");
				}
			} else if (action.equals("send_message")) {
				Cookie[] cookies = req.getCookies();
				String to = req.getParameter("to");
				String msg = req.getParameter("msg");
				String from = CookieHandler.getCookieValue(cookies, "uid");
				String ule = CookieHandler.getCookieValue(cookies, "ule");
				if (null != from && null != ule) {
					String cleanFrom = new HTMLInputFilter().filter(from);
					if (Utils.SHA256(Utils.MD5(cleanFrom)).equals(ule)) {
						Requests.add(from, to, msg);
						resp.setContentType("application/json");
						resp.getWriter().print("{\"success\":true}");
					}
				} else
					resp.sendRedirect("/#sign_in");
			} else if (action.equals("logout")) {
				resp.addCookie(CookieHandler.eraseCookie("ule"));
				resp.setContentType("application/json");
				resp.getWriter().print("{\"success\":true}");
			} else if (action.equals("get_all_msg")) {
				Cookie[] cookies = req.getCookies();
				if (null != cookies) {
					String login = CookieHandler.getCookieValue(cookies, "ule");
					ArrayList<Pair<String, String>> messages = Requests.getByReceiverAll(login);
					if (!login.equals(null)) {
						if (Users.cookieLoginSuccessful(login)) {
							if (messages.size() != 0) {
								resp.setContentType("application/json");
								resp.getWriter().print(
										"{\"success\":true,\"inbox\":{\"msg\":"
												+ Utils.toJSON(messages) + ",\"length\":"
												+ messages.size() + "}}");
							} else {
								resp.setContentType("application/json");
								resp.getWriter().print("{\"success\":true}");
							}
						}
					} else {
						resp.setContentType("application/json");
						resp.getWriter().print("{\"success\":false}");
					}
				} else {
					resp.setContentType("application/json");
					resp.getWriter().print("{\"success\":false}");
				}
			} else if (action.equals("outbox")) {
				Cookie[] cookies = req.getCookies();
				if (null != cookies) {
					String login = CookieHandler.getCookieValue(cookies, "ule");
					ArrayList<Pair<String, String>> messages = Requests.getBySender(login);
					if (!login.equals(null)) {
						if (Users.cookieLoginSuccessful(login)) {
							if (messages.size() != 0) {
								resp.setContentType("application/json");
								resp.getWriter().print(
										"{\"success\":true,\"outbox\":{\"msg\":"
												+ Utils.toJSON(messages) + ",\"length\":"
												+ messages.size() + "}}");
							} else {
								resp.setContentType("application/json");
								resp.getWriter().print("{\"success\":true}");
							}
						}
					} else {
						resp.setContentType("application/json");
						resp.getWriter().print("{\"success\":false}");
					}
				} else {
					resp.setContentType("application/json");
					resp.getWriter().print("{\"success\":false}");
				}
			}
		} else
			resp.sendRedirect("/#home");
	}
}
